import axios from 'axios';
import type { AxiosInstance } from 'axios';
import { showMessage, showError } from '../utils/message';

interface LoginCredentials {
  username: string;
  password: string;
}

interface RegisterData extends LoginCredentials {
  email: string;
  nick_name?: string;
}

interface AuthResponse {
  code: number;
  msg: string;
  data: {
    token: string;
  };
}

interface UserInfo {
  data: UserInfo | PromiseLike<UserInfo>;
  id: number;
  username: string;
  email: string;
  nick_name?: string;
  avatar?: string;
  date_joined: string;
  last_login: string;
  is_active: boolean;
  is_staff: boolean;
  points?: number;
  level?: number;
  solved_problems?: number;
  total_submissions?: number;
  accepted_submissions?: number;
}

const BASE_URL = 'http://localhost:8005/users/auth_api';

const api: AxiosInstance = axios.create({
  baseURL: BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器 - 添加token
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Token ${token}`;
    }
    return config;
  },
  (error) => {
    showError(error);
    return Promise.reject(error);
  }
);

// 响应拦截器 - 处理错误
api.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code !== 200) {
      showMessage(res);
      return Promise.reject(res);
    }
    return response;
  },
  (error) => {
    if (error.response) {
      // 处理特定的错误状态码
      switch (error.response.status) {
        case 401:
          // 未授权 - 清除token并重定向到登录页
          localStorage.removeItem('token');
          // window.location.href = '/login';
          break;
        case 400:
          // 请求错误
          console.error('请求错误:', error.response.data);
          break;
        default:
          console.error('服务器错误:', error.response.data);
      }
      showError(error.response.data);
    }
    return Promise.reject(error);
  }
);

export const authApi = {
  // 用户登录
  login: async (credentials: LoginCredentials): Promise<AuthResponse> => {
    try {
      const response = await api.post<AuthResponse>('/login/', credentials);
      localStorage.setItem('token', response.data.data.token);
      return response.data;
    } catch (error) {
      throw error;
    }
  },

  // 用户注册
  register: async (userData: RegisterData): Promise<AuthResponse> => {
    try {
      const response = await api.post<AuthResponse>('/register/', userData);
      localStorage.setItem('token', response.data.data.token);
      return response.data;
    } catch (error) {
      throw error;
    }
  },

  // 用户注销
  logout: async (): Promise<void> => {
    try {
      await api.post('/logout/');
      localStorage.removeItem('token');
    } catch (error) {
      throw error;
    }
  },

  // 检查是否已登录
  isAuthenticated: (): boolean => {
    return !!localStorage.getItem('token');
  },

  // 获取用户信息
  getUserInfo: async (): Promise<UserInfo> => {
    const response = await api.get<UserInfo>('/profile/');
    return response.data.data;
  },

  // 更新用户信息
  updateUserInfo: async (data: Partial<UserInfo>): Promise<UserInfo> => {
    const response = await api.put<UserInfo>('/update_profile/', data);
    return response.data.data;
  },
};

export default authApi;
